import 'dart:io';

import 'package:device_info_plus/device_info_plus.dart';
import 'package:flutter/services.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';

import '../service/user_storage_service.dart';

class HttpAgent {
    // 单例模式
  static final HttpAgent _instance = HttpAgent._internal();
  factory HttpAgent() => _instance;
  HttpAgent._internal();
  
  final UserStorageService _userStorage = UserStorageService();
  String? uid;
  String version = "4.0.0";
  String language = "en";
  String device = Platform.isIOS ? "1" : "2";
  String? androidid;
  String? timestamp;
  String? token  = "";

  /// 初始化异步数据（如 androidId）
  Future<void> init() async {
    uid = _userStorage.getUserId();
    token = _userStorage.getAccessToken();
    androidid = await DeviceUtils.getPersistentDeviceId();
    timestamp = (DateTime.now().millisecondsSinceEpoch ~/ 1000).toString();
  }

    /// 更新uid
  void updateUid(String? newUid) {
    uid = newUid;
  }

  void updateToken(String? newToken) {
    print("更新后的: $newToken");
    token = newToken;
  }

  /// 构造 User-Agent 字符串
  String userAgent() {
    return 'uid=${uid ?? ""};version=$version;language=$language;device=$device;androidid=${androidid ?? ""};timestamp=${timestamp ?? ""};';
  }
}



class DeviceUtils {
  static const MethodChannel _channel =
      MethodChannel('com.company.BitFury/device_info');
  static final DeviceInfoPlugin _deviceInfoPlugin = DeviceInfoPlugin();
  static final FlutterSecureStorage _secureStorage = const FlutterSecureStorage();

  static const _deviceIdKey = "persistent_device_id";

  static Future<String> getPersistentDeviceId() async {
    try {
      // 1. 先看安全存储里有没有
      String? savedId = await _secureStorage.read(key: _deviceIdKey);
      if (savedId != null && savedId.isNotEmpty) {
        print("读取已有设备ID: $savedId");
        return savedId;
      }

      // 2. 没有则获取新 ID
      String newId;
      if (Platform.isAndroid) {
        final String? androidId = await _channel.invokeMethod('getAndroidId');
        newId = androidId ?? 'android-unknown-${DateTime.now().millisecondsSinceEpoch}';
      } else if (Platform.isIOS) {
        final IosDeviceInfo iosInfo = await _deviceInfoPlugin.iosInfo;
        newId = iosInfo.identifierForVendor ?? 'ios-unknown-${DateTime.now().millisecondsSinceEpoch}';
      } else {
        newId = 'unknown-${DateTime.now().millisecondsSinceEpoch}';
      }

      // 3. 存到安全存储，下次复用
      await _secureStorage.write(key: _deviceIdKey, value: newId);
      print("生成并保存新的设备ID: $newId");
      return newId;
    } catch (e) {
      print("获取设备ID失败: $e");
      return 'unknown-${DateTime.now().millisecondsSinceEpoch}';
    }
  }
}




